package com.sp.homework;

/**
 * 1. 有两个用户分别从同一个卡上取钱(总额: 10000)
 * 2. 每次都取1000, 当余额不足时, 就不能取款了
 * 3. 不能出现超取现象(线程同步)
 */
public class Homework02 {
    public static void main(String[] args) {
        Withdraw withdraw = new Withdraw();
        Thread thread1 = new Thread(withdraw);
        Thread thread2 = new Thread(withdraw);
        thread1.start();
        thread2.start();

    }
}


//这里设计到多个线程共享资源, 所以使用实现Runnable接口的方式
class Withdraw implements Runnable {

    private int balance = 10000;//余额
    private int drawMoney = 1000;
    private boolean loop = true;

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                if (balance <= drawMoney) {
                    System.out.println(Thread.currentThread().getName() + "取钱, 但余额不足");
                    break;
                }
                balance = balance - drawMoney;
                System.out.println(Thread.currentThread().getName() + "取了" + drawMoney + "元, 还剩" + balance);
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}